#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QInputDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , addCollegeWindow(new AddCollegeWindow(this->parentWidget()))
    , addEventWindow(new AddEventWindow(this->parentWidget()))
    , addResultWindow(new AddResultWindow(this->parentWidget()))
    , displayResultsWindow(new DisplayResultsWindow(this->parentWidget()))
    , displayDataWindow(new DisplayDataWindow(this->parentWidget()))
{
    ui->setupUi(this);

    connect(ui->addCollegeButton, &QPushButton::clicked, this, &MainWindow::on_addCollegeButton_clicked);
    connect(ui->addEventButton, &QPushButton::clicked, this, &MainWindow::on_addEventButton_clicked);
    connect(ui->addResultButton, &QPushButton::clicked, this, &MainWindow::on_addResultButton_clicked);
    connect(ui->displayResultsButton, &QPushButton::clicked, this, &MainWindow::on_displayResultsButton_clicked);
    connect(ui->displayDataButton, &QPushButton::clicked, this, &MainWindow::on_displayDataButton_clicked);
    connect(ui->modifyCollegeButton, &QPushButton::clicked, this, &MainWindow::on_modifyCollegeButton_clicked);
    connect(ui->modifyEventButton, &QPushButton::clicked, this, &MainWindow::on_modifyEventButton_clicked);
    connect(ui->deleteResultButton, &QPushButton::clicked, this, &MainWindow::on_deleteResultButton_clicked);

    connect(addCollegeWindow, &AddCollegeWindow::collegeAdded, this, &MainWindow::handleCollegeAdded);
    connect(addEventWindow, &AddEventWindow::eventAdded, this, &MainWindow::handleEventAdded);
    connect(addResultWindow, &AddResultWindow::resultAdded, this, &MainWindow::handleResultAdded);

    loadData();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete addCollegeWindow;
    delete addEventWindow;
    delete addResultWindow;
    delete displayResultsWindow;
    delete displayDataWindow;
}

void MainWindow::addCollege(const QString& name) {
    College* existingCollege = collegeHead;
    while (existingCollege != nullptr) {
        if (existingCollege->name == name) {
            QMessageBox::information(this, "提示", QString("学院 %1 已存在，编号为 %2").arg(name).arg(existingCollege->id));
            return;
        }
        existingCollege = existingCollege->next;
    }

    College* newCollege = new College;
    newCollege->id = ++collegeCount;
    newCollege->name = name;
    newCollege->points = 0;
    newCollege->next = collegeHead;
    collegeHead = newCollege;
}

void MainWindow::addEvent(const QString& name, int isTopFive, bool isMale) {
    Event* existingEvent = eventHead;
    while (existingEvent != nullptr) {
        if (existingEvent->name == name && ((existingEvent->isMale && isMale) || (!existingEvent->isMale && !isMale))) {
            QMessageBox::information(this, "提示", QString("项目 %1 已存在，编号为 %2").arg(name).arg(existingEvent->id));
            return;
        }
        existingEvent = existingEvent->next;
    }

    Event* newEvent = new Event;
    newEvent->name = name;
    newEvent->isTopFive = isTopFive;
    newEvent->isMale = isMale;
    newEvent->next = eventHead;
    eventHead = newEvent;

    // 调整所有项目编号
    int maleEventCount = 0;
    Event* event = eventHead;
    while (event != nullptr) {
        if (event->isMale == 1) {
            event->id = ++maleEventCount;
        }
        event = event->next;
    }
    event = eventHead;
    while (event !=nullptr){
        if (event->isMale == 0){
            event->id = ++maleEventCount;
        }
        event = event->next;
    }

    // 重新排序项目
    Event* sortedEvents[100];
    int count = 0;
    event = eventHead;
    while (event != nullptr) {
        sortedEvents[count++] = event;
        event = event->next;
    }

    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (sortedEvents[j]->id > sortedEvents[j + 1]->id) {
                Event* temp = sortedEvents[j];
                sortedEvents[j] = sortedEvents[j + 1];
                sortedEvents[j + 1] = temp;
            }
        }
    }

    eventHead = sortedEvents[0];
    for (int i = 0; i < count - 1; i++) {
        sortedEvents[i]->next = sortedEvents[i + 1];
    }
    sortedEvents[count - 1]->next = nullptr;
}


void MainWindow::addResult(int collegeId, int eventId, int rank) {
    Result* newResult = new Result;
    newResult->collegeId = collegeId;
    newResult->eventId = eventId;
    newResult->rank = rank;
    newResult->next = resultHead;
    resultHead = newResult;

    // 更新学院积分
    College* college = collegeHead;
    while (college != nullptr) {
        if (college->id == collegeId) {
            Event* event = eventHead;
            while (event != nullptr) {
                if (event->id == eventId) {
                    if (event->isTopFive) {
                        if (rank == 1) college->points += 7;
                        else if (rank == 2) college->points += 5;
                        else if (rank == 3) college->points += 3;
                        else if (rank == 4) college->points += 2;
                        else if (rank == 5) college->points += 1;
                    } else {
                        if (rank == 1) college->points += 5;
                        else if (rank == 2) college->points += 3;
                        else if (rank == 3) college->points += 2;
                    }
                    break;
                }
                event = event->next;
            }
            break;
        }
        college = college->next;
    }
}

void MainWindow::displayResults() {
    // 按积分排序
    College* sortedColleges[100];
    int count = 0;
    College* college = collegeHead;
    while (college != nullptr) {
        sortedColleges[count++] = college;
        college = college->next;
    }

    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (sortedColleges[j]->points < sortedColleges[j + 1]->points) {
                College* temp = sortedColleges[j];
                sortedColleges[j] = sortedColleges[j + 1];
                sortedColleges[j + 1] = temp;
            }
        }
    }

    // 显示总排名
    QList<QList<QString>> results;
    for (int i = 0; i < count; i++) {
        QList<QString> row;
        row << QString::number(i + 1) << sortedColleges[i]->name << QString::number(sortedColleges[i]->points);
        results.append(row);
    }
    displayResultsWindow->displayResults(results);
    displayResultsWindow->show();
}

void MainWindow::displayCollegesAndEvents() {
    // 按学院编号排序
    College* sortedColleges[100];
    int count = 0;
    College* college = collegeHead;
    while (college != nullptr) {
        sortedColleges[count++] = college;
        college = college->next;
    }

    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (sortedColleges[j]->id < sortedColleges[j + 1]->id) {
                College* temp = sortedColleges[j];
                sortedColleges[j] = sortedColleges[j + 1];
                sortedColleges[j + 1] = temp;
            }
        }
    }

    // 逆序显示学院和项目数据
    QList<QList<QString>> data;
    for (int i = count - 1; i >= 0; i--) {
        QList<QString> row;
        row << "学院" << sortedColleges[i]->name << QString::number(sortedColleges[i]->id);
        data.append(row);
    }

    Event* sortedEvents[100];
    int eventCount = 0;
    Event* event = eventHead;
    while (event != nullptr) {
        sortedEvents[eventCount++] = event;
        event = event->next;
    }

    for (int i = 0; i < eventCount - 1; i++) {
        for (int j = 0; j < eventCount - i - 1; j++) {
            if (sortedEvents[j]->id < sortedEvents[j + 1]->id) {
                Event* temp = sortedEvents[j];
                sortedEvents[j] = sortedEvents[j + 1];
                sortedEvents[j + 1] = temp;
            }
        }
    }

    for (int i = eventCount - 1; i >= 0; i--) {
        QList<QString> row;
        row << "项目" << sortedEvents[i]->name << QString::number(sortedEvents[i]->id);
        data.append(row);
    }

    displayDataWindow->displayData(data);
    displayDataWindow->show();
}

void MainWindow::displayResultsByEvent() {
    // 按项目编号逆序排序
    QList<QList<QString>> data;
    Result* result = resultHead;
    while (result != nullptr) {
        QList<QString> row;
        Event* event = eventHead;
        while (event != nullptr) {
            if (event->id == result->eventId) {
                row << event->name;
                break;
            }
            event = event->next;
        }
        College* college = collegeHead;
        while (college != nullptr) {
            if (college->id == result->collegeId) {
                row << college->name;
                break;
            }
            college = college->next;
        }
        row << QString::number(result->rank);
        data.append(row);
        result = result->next;
    }

    displayDataWindow->displayResultsByEvent(data);
    displayDataWindow->show();
}



void MainWindow::loadData() {
    QFile file("data.txt");
    if (!file.exists()) {
        // 如果文件不存在，则创建一个空的 data.txt 文件
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::warning(this, "错误", "无法创建 data.txt 文件");
            return;
        }
        file.close();
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法打开文件进行读取");
        return;
    }

    QTextStream in(&file);

    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(" ");
        if (fields[0] == "C") {
            int id = fields[1].toInt();
            QString name = fields[2];
            int points = fields[3].toInt();
            addCollege(name);
            collegeHead->points = points;
        } else if (fields[0] == "E") {
            int id = fields[1].toInt();
            QString name = fields[2];
            int isTopFive = fields[3].toInt();
            addEvent(name, isTopFive, id % 2 == 1);
        } else if (fields[0] == "R") {
            int collegeId = fields[1].toInt();
            int eventId = fields[2].toInt();
            int rank = fields[3].toInt();
            addResult(collegeId, eventId, rank);
        }
    }

    file.close();
}


void MainWindow::saveData() {
    QFile file("data.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法打开文件进行写入");
        return;
    }

    QTextStream out(&file);

    College* college = collegeHead;
    while (college != nullptr) {
        out << "C " << college->id << " " << college->name << " " << college->points << "\n";
        college = college->next;
    }

    Event* event = eventHead;
    while (event != nullptr) {
        out << "E " << event->id << " " << event->name << " " << event->isTopFive << "\n";
        event = event->next;
    }

    Result* result = resultHead;
    while (result != nullptr) {
        out << "R " << result->collegeId << " " << result->eventId << " " << result->rank << "\n";
        result = result->next;
    }

    file.close();
}

void MainWindow::modifyCollege(int id, const QString& newName) {
    College* college = collegeHead;
    while (college != nullptr) {
        if (college->id == id) {
            college->name = newName;
            QMessageBox::information(this, "提示", QString("学院 %1 已修改为 %2").arg(id).arg(newName));
            return;
        }
        college = college->next;
    }
    QMessageBox::warning(this, "错误", QString("未找到编号为 %1 的学院").arg(id));
}

void MainWindow::modifyEvent(int id, const QString& newName, int isTopFive) {
    Event* event = eventHead;
    while (event != nullptr) {
        if (event->id == id) {
            event->name = newName;
            event->isTopFive = isTopFive;
            QMessageBox::information(this, "提示", QString("项目 %1 已修改为 %2").arg(id).arg(newName));
            return;
        }
        event = event->next;
    }
    QMessageBox::warning(this, "错误", QString("未找到编号为 %1 的项目").arg(id));
}

void MainWindow::deleteResult(int collegeId, int eventId) {
    Result* prevResult = nullptr;
    Result* result = resultHead;
    while (result != nullptr) {
        if (result->collegeId == collegeId && result->eventId == eventId) {
            // 更新学院积分
            College* college = collegeHead;
            while (college != nullptr) {
                if (college->id == collegeId) {
                    Event* event = eventHead;
                    while (event != nullptr) {
                        if (event->id == eventId) {
                            if (event->isTopFive) {
                                if (result->rank == 1) college->points -= 7;
                                else if (result->rank == 2) college->points -= 5;
                                else if (result->rank == 3) college->points -= 3;
                                else if (result->rank == 4) college->points -= 2;
                                else if (result->rank == 5) college->points -= 1;
                            } else {
                                if (result->rank == 1) college->points -= 5;
                                else if (result->rank == 2) college->points -= 3;
                                else if (result->rank == 3) college->points -= 2;
                            }
                            break;
                        }
                        event = event->next;
                    }
                    break;
                }
                college = college->next;
            }

            // 删除结果节点
            if (prevResult == nullptr) {
                resultHead = result->next;
            } else {
                prevResult->next = result->next;
            }
            free(result);
            QMessageBox::information(this, "提示", QString("已删除学院 %1 的项目 %2 的名次和积分").arg(collegeId).arg(eventId));
            saveData(); // 保存数据
            return;
        }
        prevResult = result;
        result = result->next;
    }
    QMessageBox::warning(this, "错误", QString("未找到学院 %1 的项目 %2 的名次和积分").arg(collegeId).arg(eventId));
}


void MainWindow::handleCollegeAdded(const QString &name)
{
    addCollege(name);
    saveData();
}

void MainWindow::handleEventAdded(const QString &name, int isTopFive, bool isMale)
{
    addEvent(name, isTopFive, isMale);
    saveData();
}

void MainWindow::handleResultAdded(int collegeId, int eventId, int rank)
{
    addResult(collegeId, eventId, rank);
    saveData();
}

void MainWindow::on_addCollegeButton_clicked()
{
    qDebug() << "Add College Button clicked";
    addCollegeWindow->show();
}

void MainWindow::on_addEventButton_clicked()
{
    qDebug() << "Add Event Button clicked";
    addEventWindow->show();
}

void MainWindow::on_addResultButton_clicked()
{
    qDebug() << "Add Result Button clicked";
    addResultWindow->show();
}

void MainWindow::on_displayResultsButton_clicked()
{
    qDebug() << "Display Results Button clicked";
    displayResults();
}

void MainWindow::on_displayDataButton_clicked()
{
    qDebug() << "Display Data Button clicked";
    displayCollegesAndEvents();
}

void MainWindow::on_displayResultsByEventButton_clicked()
{
    qDebug() << "Display Results By Event Button clicked";
    displayResultsByEvent();
}

void MainWindow::on_modifyCollegeButton_clicked()
{
    qDebug() << "Modify College Button clicked";
    bool ok;
    int id = QInputDialog::getInt(this, "修改学院", "请输入学院编号:", 0, 0, 10000, 1, &ok);
    if (!ok) return;

    QString newName = QInputDialog::getText(this, "修改学院", "请输入新的学院名称:", QLineEdit::Normal, "", &ok);
    if (!ok || newName.isEmpty()) return;

    modifyCollege(id, newName);
}

void MainWindow::on_modifyEventButton_clicked()
{
    qDebug() << "Modify Event Button clicked";
    bool ok;
    int id = QInputDialog::getInt(this, "修改项目", "请输入项目编号:", 0, 0, 10000, 1, &ok);
    if (!ok) return;

    QString newName = QInputDialog::getText(this, "修改项目", "请输入新的项目名称:", QLineEdit::Normal, "", &ok);
    if (!ok || newName.isEmpty()) return;

    int isTopFive = QInputDialog::getInt(this, "修改项目", "是否取前五名(1是, 0否):", 0, 0, 1, 1, &ok);
    if (!ok) return;

    modifyEvent(id, newName, isTopFive);
}

void MainWindow::on_deleteResultButton_clicked()
{
    qDebug() << "Delete Result Button clicked";
    bool ok;
    int collegeId = QInputDialog::getInt(this, "删除比赛结果", "请输入学院编号:", 0, 0, 10000, 1, &ok);
    if (!ok) return;

    int eventId = QInputDialog::getInt(this, "删除比赛结果", "请输入项目编号:", 0, 0, 10000, 1, &ok);
    if (!ok) return;

    deleteResult(collegeId, eventId);
}
